<template>
  <el-upload
    ref="uploadRef"
    class="upload-demo"
    :action="data.postUrl"
    :data="data"
    :file-list="data.fileList"
    multiple
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="3"
    :on-exceed="handleExceed"
    :on-success="uploadSuccess"
    :auto-upload="false"
  >
  <template #trigger>
      <el-button type="primary">select file</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload">
      upload to server
    </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">
        limit 3 file, new file will cover the old file
      </div>
    </template>
  </el-upload>
</template>
<script setup>
import { ref,reactive,onMounted } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'
const data = reactive({
	    fileName: "file",//用于指定上传文件的字段名，也就是在后端接收上传文件时需要使用的字段名。在前端发送上传请求时，请求头中会包含该字段名和对应的文件数据，后端就可以通过这个字段名获取到上传的文件数据
         fileList:[],
         postUrl :""
      })
      
const uploadRef = ref(null)

const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}

const beforeRemove= (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfert of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}

    //上传文件成功
    const uploadSuccess = (response, file, fileList) => {
		      data.fileList.push({//得到的文件数据转换成 name url方式
		        name: file.fileOrigName,
		        url: file.filePreviewUrl
		      });
    };

    const submitUpload = () => {
      //手动提交
      uploadRef.value.submit();
}

    onMounted(async () => {
      data.postUrl = "/api/uploadFile";
    });
</script>

